package com.hlingsoft.cms.action;


import com.hlingsoft.cms.constant.OrderInfoConstant;
import com.hlingsoft.cms.dao.*;
import com.hlingsoft.cms.entity.*;
import com.hlingsoft.cms.entity.vo.OrderDetailVo;
import com.hlingsoft.cms.entity.vo.OrderInfoListVo;
import com.hlingsoft.cms.util.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by selbylei on 2015/5/5.
 */

@Controller
@RequestMapping("/order")
public class OrderInfoAction extends BaseAction {


    /**
     * 提交订单
     *
     * @param appUserId
     * @param goodsId
     * @param goodsCount
     * @param sizeWithPriceId
     * @param consigneeId
     * @param couponId
     * @param otherReq
     * @param request
     * @return
     */
    @RequestMapping(value = "/add.json")
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "goodsId") long goodsId,
            @RequestParam(value = "goodsCount") int goodsCount,
            @RequestParam(value = "sizeWithPriceId") long sizeWithPriceId,
            @RequestParam(value = "consigneeId") long consigneeId,
            @RequestParam(value = "couponId", required = false) Integer couponId,
            @RequestParam(value = "otherReq") String otherReq,
            @RequestParam(value = "orderName", required = false) String orderName,
            @RequestParam(value = "orderPhone", required = false) String orderPhone,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Date now = new Date();
            OrderInfo orderInfo = new OrderInfo();

            AppUser appUser = appUserDao.getUserById(appUserId);
            orderInfo.setAppUserId(appUserId);
            orderInfo.setGoodsId(goodsId);
            //商品数量
            orderInfo.setGoodsCount(goodsCount);
            //商品尺寸价格
            SizeWithPrice sizeWithPrice = sizeWithPriceDao.getSizeWithPriceById(sizeWithPriceId);
            orderInfo.setGoodsSize(sizeWithPrice.getSize());
            orderInfo.setGoodsPrice(sizeWithPrice.getPrice());    //单价
            //商品图片
            List<Image> imageList = imageDao.getImageByGoodsId(goodsId, 1);
            orderInfo.setGoodImage(imageList.get(0).getPath());

            //商品价格
            Double goodsTotalPrice = orderInfo.getGoodsPrice() * goodsCount;
            orderInfo.setGoodsTotalPrice(goodsTotalPrice);


            //配送费
            Double shippingPrice = Double.valueOf(0);
            Goods goods = goodsDao.getGoodsById(goodsId);
            if (goods != null) {
                shippingPrice = goods.getShippingPrice();
            }
            orderInfo.setShippingPrice(shippingPrice);


            //收货地址
            orderInfo.setConsigneeId(consigneeId);
            Consignee consignee = consigneeDao.getConsigneeById(consigneeId);
            if (consignee != null) {
                orderInfo.setConsigneeName(consignee.getName());
                orderInfo.setConsigneeAddress(consignee.getArea() + consignee.getAddress());
                orderInfo.setConsigneePhone(consignee.getPhone());
                //收货地址不在黄埔区和静安区
                if (consignee.getArea().contains("黄埔区") || consignee.getArea().contains("静安区")) {
                    orderInfo.setShippingPrice(Double.valueOf(0));
                   shippingPrice = Double.valueOf(0);
                }
            }

            orderInfo.setConsigneeTime("下单后24小时发货");
            orderInfo.setOtherReq(otherReq);
            orderInfo.setStatus(OrderInfoConstant.WAITPAY);


            //代金券
            if (couponId != null) {
                orderInfo.setCouponId(couponId);                        //代金券id
                Coupon coupon = couponDao.getCouponById(couponId);
                double couponPrice = coupon.getPrice();
                orderInfo.setCouponPrice(couponPrice);                  //代金券金额
                orderInfo.setPayPrice(goodsTotalPrice + shippingPrice - couponPrice);  //总金额
            } else {
                orderInfo.setPayPrice(goodsTotalPrice + shippingPrice);
            }
            orderInfo.setPayType(OrderInfoConstant.COD);
            orderInfo.setShippingType(OrderInfoConstant.HOME);
            orderInfo.setName(goodsDao.getGoodsById(goodsId).getName());
            orderInfo.setOrderId(Common.getOrderNo());
            if (orderName != null) {
                orderInfo.setOrderName(orderName);
            } else {
                orderInfo.setOrderName(appUser.getName());
            }
            if (orderPhone != null) {
                orderInfo.setOrderPhone(orderPhone);
            } else {
                if (appUser.getType() == 1) {
                    orderInfo.setOrderPhone(appUser.getPhone());
                } else {
                    orderInfo.setOrderPhone("第三方登陆,无法查实电话");
                }
            }
            orderInfo.setCreateTime(now);
            orderInfo.setUpdateTime(now);
            orderInfoDao.addOrderInfo(orderInfo);

            resultMap.put("orderInfo", orderInfo);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 制作蛋糕后生产订单
     *
     * @param appUserId
     * @param goodName
     * @param tagsId
     * @param goodsCount
     * @param consigneeId
     * @param otherReq
     * @param couponId
     * @param shippingPrice
     * @param request
     * @return
     */
    @RequestMapping(value = "/autoAdd.json")
    @ResponseBody
    public Map<String, Object> autoAdd(
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "tagsId") long tagsId,
            @RequestParam(value = "goodName") String goodName,
            @RequestParam(value = "goodsCount") int goodsCount,
            @RequestParam(value = "consigneeId") long consigneeId,
            @RequestParam(value = "otherReq") String otherReq,
            @RequestParam(value = "couponId", required = false) Integer couponId,
            @RequestParam(value = "shippingRates", required = false) Integer shippingPrice,
            @RequestParam(value = "orderName", required = false) String orderName,
            @RequestParam(value = "orderPhone", required = false) String orderPhone,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser appUser = appUserDao.getUserById(appUserId);
            Date now = new Date();
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderId(Common.getOrderNo());
            orderInfo.setAppUserId(appUserId);
            orderInfo.setGoodsId(0);
            orderInfo.setGoodsCount(goodsCount);
            orderInfo.setGoodsSize("待定尺寸");
            orderInfo.setGoodsPrice(0.0);
            Tags tags = tagsDao.getTagsById(tagsId);
            orderInfo.setGoodImage(tags.getPath());
            orderInfo.setConsigneeId(consigneeId);
            Consignee consignee = consigneeDao.getConsigneeById(consigneeId);

            if (shippingPrice != null) {
                orderInfo.setShippingPrice(shippingPrice.doubleValue());       //配送费
            } else {
                orderInfo.setShippingPrice(Double.valueOf(0));
            }

            if (consignee != null) {
                orderInfo.setConsigneeName(consignee.getName());
                orderInfo.setConsigneeAddress(consignee.getArea() + consignee.getAddress());
                orderInfo.setConsigneePhone(consignee.getPhone());

                //收货地址不在黄埔区和静安区
                if (consignee.getArea().contains("黄埔区") || consignee.getArea().contains("静安区")) {
                    orderInfo.setShippingPrice(Double.valueOf(0));
                }
            }
            orderInfo.setTagsId(tagsId);

            orderInfo.setConsigneeTime("等待后台审核");
            orderInfo.setOtherReq(otherReq);


            orderInfo.setGoodsTotalPrice(0.0);      //商品价格

            if (couponId != null) {
                orderInfo.setCouponId(couponId);
                orderInfo.setCouponPrice(couponDao.getCouponById(couponId).getPrice());
            } else {
                orderInfo.setCouponId(0);
                orderInfo.setCouponPrice(Double.valueOf(0));
            }
            orderInfo.setPayType(OrderInfoConstant.COD);
            orderInfo.setShippingType(OrderInfoConstant.HOME);
            orderInfo.setName(goodName);
            orderInfo.setGoodsPrice(Double.valueOf(0));
            orderInfo.setPayPrice(Double.valueOf(0));

            if (orderName != null) {
                orderInfo.setOrderName(orderName);
            } else {
                orderInfo.setOrderName(appUser.getName());
            }
            if (orderPhone != null) {
                orderInfo.setOrderPhone(orderPhone);
            } else {
                if (appUser.getType() == 1) {
                    orderInfo.setOrderPhone(appUser.getPhone());
                } else {
                    orderInfo.setOrderPhone("第三方登陆,无法查实电话");
                }
            }
            orderInfo.setStatus(OrderInfoConstant.CHECK);            //等待后台审核
            orderInfo.setCreateTime(now);
            orderInfo.setUpdateTime(now);
            orderInfoDao.addOrderInfo(orderInfo);

            resultMap.put("orderInfo", orderInfo);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 订单列表
     *
     * @param appUserId
     * @param request
     * @return
     */
    @RequestMapping(value = "/list.json")
    @ResponseBody
    public Map<String, Object> list(
            @RequestParam(value = "appUserId") long appUserId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<OrderInfoListVo> orderInfoListVoList = new ArrayList<OrderInfoListVo>();
            List<OrderInfo> orderInfoList = orderInfoDao.getOrderInfoByAppUserId(appUserId);
            for (OrderInfo orderInfo : orderInfoList) {
                OrderInfoListVo orderInfoListVo = new OrderInfoListVo();
                orderInfoListVo.setId(orderInfo.getId());
                orderInfoListVo.setSize(orderInfo.getGoodsSize());
                orderInfoListVo.setName(orderInfo.getName());
                orderInfoListVo.setPayPrice(orderInfo.getPayPrice());
                orderInfoListVo.setOrderId(orderInfo.getOrderId());
                orderInfoListVo.setCount(orderInfo.getGoodsCount());
                orderInfoListVo.setCreateTime(orderInfo.getCreateTime());
                orderInfoListVo.setStatus(orderInfo.getStatus());
                orderInfoListVo.setNow(new Date());
                orderInfoListVo.setShowImage(orderInfo.getGoodImage());
                orderInfoListVo.setSize(orderInfo.getGoodsSize());
                orderInfoListVoList.add(orderInfoListVo);
            }
            resultMap.put("orderInfoListVoList", orderInfoListVoList);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 取消订单
     *
     * @param orderInfoId
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete.json")
    @ResponseBody
    public Map<String, Object> delete(
            @RequestParam(value = "orderInfoId") long orderInfoId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            OrderInfo orderInfo = orderInfoDao.getOrderById(orderInfoId);
            if (orderInfo != null) {
                if (orderInfo.getStatus() == OrderInfoConstant.WAITPAY) {
                    orderInfo.setStatus(OrderInfoConstant.CANCEL);
                    orderInfoDao.updateOrderInfo(orderInfo);
                    resultMap.put("result", true);
                } else {
                    resultMap.put("msg", "无法取消订单");
                    resultMap.put("result", false);
                }

            } else {
                resultMap.put("msg", "订单不存在");
                resultMap.put("result", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 详情页
     *
     * @param orderInfoId
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "orderInfoId") long orderInfoId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            OrderInfo orderInfo = orderInfoDao.getOrderById(orderInfoId);
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            if (orderInfo != null) {

                orderDetailVo.setId(orderInfo.getId());
                orderDetailVo.setOrderId(orderInfo.getOrderId());
                orderDetailVo.setStatus(orderInfo.getStatus());
                if (orderInfo.getStatus() == OrderInfoConstant.WAITPAY) {
                    orderDetailVo.setIsCancel(1);
                } else {
                    orderDetailVo.setIsCancel(0);
                }
                orderDetailVo.setPayPrice(orderInfo.getPayPrice());
                orderDetailVo.setPayType(orderInfo.getPayType());
                orderDetailVo.setName(orderInfo.getName());
                orderDetailVo.setShippingPrice(orderInfo.getShippingPrice());
                orderDetailVo.setShippingType(orderInfo.getShippingType());

                SimpleDateFormat df = new SimpleDateFormat("yyyy-M-dd HH:mm:ss");
                Date d = orderInfo.getCreateTime();
                String startTime = df.format(new Date(d.getTime() + 12 * 60 * 60 * 1000));
                String endTime = df.format(new Date(d.getTime() + 14 * 60 * 60 * 1000));
                String[] sourceStrArray = endTime.split(" ");
                String shippingTime = startTime + "~" + sourceStrArray[1];
                orderDetailVo.setShippingTime(shippingTime);

                Consignee consignee = consigneeDao.getConsigneeById(orderInfo.getConsigneeId());
                if (consignee != null) {
                    String shippingContact = consignee.getName() + consignee.getPhone();
                    orderDetailVo.setShippingContact(shippingContact);
                    orderDetailVo.setShippingAddress(consignee.getAddress());
                    resultMap.put("orderDetailVo", orderDetailVo);
                    resultMap.put("result", true);
                } else {
                    //地址更新取消之前的订单
                    resultMap.put("msg", "您更新了收货地址，请重新下单");
                    resultMap.put("result", false);
                    orderInfo.setStatus(OrderInfoConstant.CANCEL);
                    orderInfoDao.updateOrderInfo(orderInfo);
                }
            } else {
                resultMap.put("msg", "订单不存在");
                resultMap.put("result", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }
}
